#!/usr/bin/env python
#-*- coding:utf-8 -*- 

from numpy import *
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import accuracy_score


with open("dataset_circles.csv", 'r') as f:  #打开文件
    columns = f.readline()  #读第一行
columns = columns.split(',')	#分割
columns = [float(i) for i in columns]	#转float
#print(type(columns), columns)

dataset = pd.read_csv("dataset_circles.csv", header=0, index_col=0)


dataset_dict = dataset.iloc[:, 0].to_dict()	#dataFrame转换成dict会丢掉columns，所以先记录下columns

dataset_x = list(dataset_dict.keys())	#取dict的keys值作为x并把丢失的columns部分插入到头部，一下同理
dataset_x.insert(0, columns[0])
dataset_y = list(dataset_dict.values())
dataset_y.insert(0, columns[1])	
dataset_x_y = list(zip(dataset_x,dataset_y))
dataset_x_y_list = [list(i) for i in dataset_x_y]
dataset_x_y = array(dataset_x_y_list)

dataset_end = dataset.iloc[:, 1].tolist()
dataset_end.insert(0, columns[2])
dataset_x_y_end = list(zip(dataset_x_y,dataset_end))

# print(dataset_x[200:])
plt.figure('原始数据')
plt.scatter(dataset_x[:200], dataset_y[:200])
plt.scatter(dataset_x[200:], dataset_y[200:])

# print(dataset_x)
# print(dataset_y)
# print(dataset_x_y)
# print(dataset_end)

############## 未变换特征  ################
y_pred_1 = KMeans(n_clusters=2, random_state=9).fit_predict(dataset_x_y)
plt.figure('未变换特征')
plt.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1], c=y_pred_1)	#未做特征变换


############## 变换特征  ################
import math
import numpy as np

dataset_r_theta_list = []
for x in dataset_x_y_list:
	r=math.sqrt(math.pow(x[0],2)+math.pow(x[1],2))
	theta=math.atan2(x[1],x[0])#转换为角度
	x[0], x[1] = theta, r
	dataset_r_theta_list.append(x)

dataset_r_theta = array(dataset_r_theta_list)

# plt.figure('原始数据(极坐标）')
# ax0 = plt.subplot(projection='polar')
# ax0.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1])	#原始数据在极坐标下表示

y_pred_2 = KMeans(n_clusters=2, random_state=9).fit_predict(dataset_r_theta)
plt.figure('变换特征-n_clusters=2')
# ax1 = plt.subplot(projection='polar')
# ax1.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1], c=y_pred_2)	#特征变换
plt.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1], c=y_pred_2)

y_pred_3 = KMeans(n_clusters=3, random_state=9).fit_predict(dataset_r_theta)
plt.figure('变换特征-n_clusters=3')
# ax1 = plt.subplot(projection='polar')
# ax1.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1], c=y_pred_2)	#特征变换
plt.scatter(dataset_x_y[:, 0], dataset_x_y[:, 1], c=y_pred_3)

plt.show()	


print('accuracy_score:', accuracy_score(dataset_end, y_pred_2)) #真值和预测值的0和1的lable刚好相反，所以精度为0，实际上是100%



